package cn.cuilan.client.procyserver;

import cn.cuilan.client.constant.UriWhiteList;
import cn.cuilan.client.core.ClientHelper;
import cn.cuilan.common.entity.HttpEntity;
import cn.cuilan.common.entity.ProtocolMessage;
import cn.cuilan.common.utils.HttpHelper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
public class ProxyServerHandler extends ChannelHandlerAdapter {

    private HttpHelper httpHelper = new HttpHelper();

    @Resource
    private ClientHelper clientHelper;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            final FullHttpRequest request = (FullHttpRequest) msg;

            String uri = request.getUri();
            if (UriWhiteList.contains(uri)) {
                return;
            }
            log.info("HTTP request: {}", uri);

            ByteBuf byteBuf = request.content();
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            log.info(new String(bytes, StandardCharsets.UTF_8));

//            HttpMethod method = request.getMethod();
//
//            if (UriWhiteList.contains(uri)) {
//                HttpHeaders headers = request.headers();
//                Iterator<Map.Entry<String, String>> iterator = headers.iterator();
//                Map<String, String> requestHeaders = new HashMap<>();
//                while (iterator.hasNext()) {
//                    Map.Entry<String, String> header = iterator.next();
//                    requestHeaders.put(header.getKey(), header.getValue());
//                }
//                // TODO 本地触发请求
//                if (method == HttpMethod.GET) {
//                    httpHelper.get(uri, requestHeaders);
//                }
//                return;
//            }
//
//            // TODO HTTPS
//            if (method == HttpMethod.CONNECT) {
//                log.info("HTTPS request: {}", uri);
//            }
        }
        HttpEntity requestEntity = new HttpEntity();
        // 对象池获取
        ProtocolMessage responseEntity = clientHelper.doSendWithNetty(requestEntity);

//        ByteBuf content = Unpooled.copiedBuffer(body, StandardCharsets.UTF_8);
//
        // 拦截请求，并转发

        FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        httpResponse.headers().set("Content-Type", "text/html;charset=UTF-8");
//        httpResponse.content().writeBytes(content);
        ctx.writeAndFlush(httpResponse);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 调用flush方法，将消息全部写入SocketShannel中
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 当发生异常时关闭并释放ChannelHandlerContext
        ctx.close();
    }
}
